<!-- filename: components/CommentModal/CommentModal.vue -->
<template>
  <view class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">评论 ({{ totalComments }})</text>
        <view class="close-btn" @click="closeModal">×</view>
      </view>

      <scroll-view class="modal-body" scroll-y>
        <view v-if="isLoading" class="loading-state">正在加载评论...</view>
        <view v-else-if="comments.length === 0" class="empty-state">还没有评论，快来抢沙发吧！</view>
        
        <view v-else class="comment-list">
          <!-- 遍历顶层评论 -->
          <view v-for="comment in comments" :key="comment.id" class="comment-item-wrapper" :class="{ highlight: !highlightParentId && comment.id === highlightCommentId }">
            <view class="comment-item">
              <!-- 优先显示头像图片 -->
              <view class="avatar-wrapper-link" @click="navigateToUserProfile(comment.user_id)">
                <image v-if="comment.avatar_url" :src="comment.avatar_url" class="avatar-image" mode="aspectFill"/>
                <view v-else class="avatar-placeholder">{{ comment.username.charAt(0).toUpperCase() }}</view>
              </view> 
              <div class="comment-main">
                <view class="comment-header">
                  <view class="username-link" @click="navigateToUserProfile(comment.user_id)">
                    <text class="username">{{ comment.username }}</text>
                  </view>
                  <text class="timestamp">{{ comment.created_at }}</text>
                </view>
                <view class="content">{{ comment.content }}</view>
                <view class="comment-actions">
                  <view class="action-btn like-btn" :class="{ 'liked': comment.liked_by_user }" @click="likeComment(comment)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
                    <text>{{ comment.like_count > 0 ? comment.like_count : '' }}</text>
                  </view>
                  <view class="action-btn reply-btn" @click="setReplyTo(comment)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/></svg>
                  </view>
                  <!-- 【新增】删除和修改按钮 -->
                  <view v-if="authStore.user && authStore.user.id === comment.user_id" class="action-btn edit-btn" @click="editComment(comment)">
                    <text>修改</text>
                  </view>
                  <view v-if="authStore.user && authStore.user.id === comment.user_id" class="action-btn delete-btn" @click="deleteComment(comment.id)">
                    <text>删除</text>
                  </view>
                </view>
              </div>
            </view>

            <!-- 【新增】回复区域 -->
            <view v-if="comment.reply_count > 0" class="replies-section">
              <!-- 回复列表 -->
              <view v-if="comment.replies && comment.replies.length > 0" class="reply-list">
                <view v-for="reply in comment.replies" :key="reply.id" class="comment-item reply-item" :class="{ highlight: reply.id === highlightCommentId }">
                  <!-- 优先显示头像图片 -->
                  <view class="avatar-wrapper-link" @click="navigateToUserProfile(reply.user_id)">
                    <image v-if="reply.avatar_url" :src="reply.avatar_url" class="avatar-image small" mode="aspectFill"/>
                    <view v-else class="avatar-placeholder small">{{ reply.username.charAt(0).toUpperCase() }}</view>
                  </view>
                   <div class="comment-main">
                     <view class="comment-header">
                       <view class="username-link" @click="navigateToUserProfile(reply.user_id)">
                        <text class="username">{{ reply.username }}</text>
                       </view>
                       <text class="timestamp">{{ reply.created_at }}</text>
                     </view>
                     <view class="content">{{ reply.content }}</view>
                     <!-- 回复的交互按钮 (简化) -->
                     <view class="comment-actions">
                       <view class="action-btn like-btn" :class="{ 'liked': reply.liked_by_user }" @click="likeComment(reply)">
                         <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
                         <text>{{ reply.like_count > 0 ? reply.like_count : '' }}</text>
                       </view>
                       <view v-if="authStore.user && authStore.user.id === reply.user_id" class="action-btn delete-btn" @click="deleteComment(reply.id)">
                         <text>删除</text>
                       </view>
                     </view>
                   </div>
                </view>
              </view>
              <!-- 查看回复按钮 -->
              <view v-if="!comment.replies_loaded_all" class="view-replies-btn" @click="fetchReplies(comment)">
                {{ comment.is_loading_replies ? '加载中...' : `查看全部 ${comment.reply_count} 条回复` }}
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="modal-footer">
        <view class="comment-input-area">
          <input 
            v-model="newCommentContent"
            :placeholder="inputPlaceholder"
            class="comment-input"
            confirm-type="send"
            @confirm="postComment"
            @blur="() => { if (!newCommentContent) replyingTo = null }"
          />
          <button class="send-btn" @click="postComment">发送</button>
        </view>
      </view>
    </view>
  </view>
</template>


<script setup>
import { ref, onMounted, computed } from 'vue';
import { useAuthStore } from '@/store/auth';
import { request } from "@/utils/request"; // 【核心修改1】

const props = defineProps({
  targetType: { type: String, required: true },
  targetId: { type: [Number, String], required: true },
  highlightParentId: { type: Number, default: null },
  highlightCommentId: { type: Number, default: null },
});
const emit = defineEmits(['close', 'update:commentCount']);

const authStore = useAuthStore();
const comments = ref([]);
const totalComments = ref(0);
const isLoading = ref(true);
const newCommentContent = ref('');
const replyingTo = ref(null);
const editingComment = ref(null);

const inputPlaceholder = computed(() => {
  if (editingComment.value) return '正在修改评论...';
  if (replyingTo.value) return `回复 @${replyingTo.value.username}:`;
  return '留下你的精彩评论...';
});

const closeModal = () => emit('close');

// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchComments = () => {
  return new Promise(async (resolve, reject) => {
    isLoading.value = true;
    try {
      const data = await request({
        url: `/api/comments/?target_type=${props.targetType}&target_id=${props.targetId}`,
        method: 'GET'
      });
      if (data && data.comments) {
        data.comments.forEach(c => {
          c.replies = [];
          c.is_loading_replies = false;
          c.replies_loaded_all = false;
        });
        comments.value = data.comments;
        totalComments.value = data.pagination.total_items || 0;
        emit('update:commentCount', totalComments.value);
      }
      resolve();
    } catch (error) {
      console.error("Failed to fetch comments:", error);
      reject(error);
    } finally {
      isLoading.value = false;
    }
  });
};

const fetchReplies = async (comment) => {
  if (comment.is_loading_replies) return;
  comment.is_loading_replies = true;
  try {
    const data = await request({
      url: `/api/comments/?target_type=${props.targetType}&target_id=${props.targetId}&parent_comment_id=${comment.id}`,
      method: 'GET'
    });
    if (data && data.comments) {
      comment.replies = data.comments.reverse();
      comment.replies_loaded_all = true;
    }
  } catch (error) {
    console.error("Failed to fetch replies:", error);
  } finally {
    comment.is_loading_replies = false;
  }
};

const postComment = async () => {
  if (!authStore.isLoggedIn) {
    emit('close');
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  if (!newCommentContent.value.trim()) {
    uni.showToast({ title: '内容不能为空', icon: 'none' });
    return;
  }

  if (editingComment.value) {
    uni.showLoading({ title: '正在修改...' });
    try {
      await request({
        url: `/api/comments/${editingComment.value.id}`,
        method: 'PUT',
        data: {
          target_type: props.targetType,
          content: newCommentContent.value
        },
      });
      uni.showToast({ title: '修改成功', icon: 'success' });
      editingComment.value.content = newCommentContent.value;
      newCommentContent.value = '';
      editingComment.value = null;
    } catch (error) {
      uni.showToast({ title: error?.data?.error || '修改失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  } else {
    const isReply = !!replyingTo.value;
    const parentComment = replyingTo.value;
    uni.showLoading({ title: '发送中...' });
    try {
      await request({
        url: `/api/comments/`,
        method: 'POST',
        data: {
          target_type: props.targetType,
          target_id: props.targetId,
          content: newCommentContent.value,
          parent_comment_id: isReply ? parentComment.id : null
        },
      });
      newCommentContent.value = '';
      replyingTo.value = null;
      if (isReply) {
        parentComment.reply_count++;
        fetchReplies(parentComment);
      } else {
        fetchComments();
      }
    } catch (error) {
      uni.showToast({ title: error?.data?.error || '发布失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  }
};

const likeComment = async (comment) => {
  if (!authStore.isLoggedIn) {
    emit('close');
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  const originalLiked = comment.liked_by_user;
  const originalCount = comment.like_count;
  comment.liked_by_user = !originalLiked;
  comment.like_count += comment.liked_by_user ? 1 : -1;
  
  try {
    const data = await request({
      url: `/api/comments/${comment.id}/like?target_type=${props.targetType}`,
      method: comment.liked_by_user ? 'POST' : 'DELETE',
    });
    comment.like_count = data.like_count;
  } catch (error) {
    comment.liked_by_user = originalLiked;
    comment.like_count = originalCount;
  }
};

const deleteComment = (commentId) => {
  emit('close');
  setTimeout(() => {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？其下的所有回复也将被一并删除。',
      success: async (res) => {
        if (res.confirm) {
          uni.showLoading({ title: '删除中...' });
          try {
            await request({
              url: `/api/comments/${commentId}?target_type=${props.targetType}`,
              method: 'DELETE',
            });
            uni.showToast({ title: '删除成功', icon: 'success' });
            fetchComments();
          } catch (error) {
            uni.showToast({ title: error?.data?.error || '删除失败', icon: 'none' });
          } finally {
            uni.hideLoading();
          }
        }
      }
    });
  }, 200);
};


// --- 无需修改的函数 ---
const navigateToUserProfile = (userId) => {
  if (userId === null || userId === undefined) {
    uni.showToast({ title: '无法查看该用户', icon: 'error' });
    return;
  }
  if (!authStore.isLoggedIn) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    emit('close');
    return;
  }
  if (authStore.user && authStore.user.id === userId) {
    uni.switchTab({ url: '/pages/profile/profile' });
    emit('close');
    return;
  }
  uni.navigateTo({ url: `/pages/user-profile/user-profile?id=${userId}` });
};

const setReplyTo = (comment) => {
  if (!authStore.isLoggedIn) {
    emit('close');
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  editingComment.value = null;
  replyingTo.value = comment;
};

const editComment = (comment) => {
  replyingTo.value = null;
  editingComment.value = comment;
  newCommentContent.value = comment.content;
};

onMounted(() => {
  fetchComments().then(() => {
    if (props.highlightParentId && props.highlightCommentId) {
      const parentComment = comments.value.find(c => c.id === props.highlightParentId);
      if (parentComment) {
        fetchReplies(parentComment);
      }
    }
  });
});
</script>

<style scoped lang="scss">
/* --- 模态框基础样式 --- */
.modal-overlay {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex; align-items: flex-end; /* 从底部弹出 */
  justify-content: center;
  z-index: 2000;
}
.modal-content {
  width: 100%; max-width: 800px; /* 与播放器对齐 */
  height: 70vh; /* 占据70%的视口高度 */
  background-color: white;
  border-radius: 16px 16px 0 0;
  display: flex; flex-direction: column;
}
.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  text-align: center;
  position: relative;
}
.modal-title {
  font-size: 16px; font-weight: bold;
}
.close-btn {
  position: absolute; top: 50%; right: 20px;
  transform: translateY(-50%);
  font-size: 24px; color: #888; cursor: pointer;
}
.modal-body {
  flex-grow: 1;
  overflow-y: auto;
}
.loading-state, .empty-state {
  text-align: center; color: #888; padding: 50px 20px;
}

/* --- 评论列表 --- */
.comment-list {
  padding: 10px 20px;
}
.comment-item {
  display: flex;
  gap: 12px;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}
.avatar-placeholder,
.avatar-image {
  width: 36px; height: 36px; border-radius: 50%;
  background-color: #007aff; color: white;
  display: flex; align-items: center; justify-content: center;
  font-size: 16px; flex-shrink: 0;
}
.avatar-image {
  background-color: #f0f0f0;
}

/* 回复区域的小头像 */
.reply-item .avatar-placeholder,
.reply-item .avatar-image {
  width: 28px;
  height: 28px;
  font-size: 12px;
}
.comment-main {
  flex-grow: 1;
}
.comment-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 5px;
}
.username {
  font-size: 14px; font-weight: 500;
}
.timestamp {
  font-size: 12px; color: #aaa;
}
.content {
  font-size: 15px; line-height: 1.6;
}
.comment-actions {
  display: flex; justify-content: flex-end; gap: 20px;
  margin-top: 8px;
}
.action-btn {
  display: flex; align-items: center; gap: 5px;
  font-size: 12px; color: #666; cursor: pointer;
  &.liked { color: #e5245e; }
}

/* --- 底部输入框 --- */
.modal-footer {
  padding: 10px 20px;
  border-top: 1px solid #eee;
  background-color: #f7f7f7;
}
.comment-input-area {
  display: flex;
  gap: 10px;
}
.comment-input {
  flex-grow: 1;
  height: 40px;
  padding: 0 12px;
  border-radius: 20px;
  background-color: #fff;
  border: 1px solid #ddd;
}
.send-btn {
  height: 40px;
  line-height: 40px;
  background-color: #007aff;
  color: white;
  font-size: 14px;
}
/* --- 【新增】回复区域样式 --- */
.replies-section {
  margin-left: 48px; /* 与头像+间距的宽度对齐 */
  padding-top: 10px;
}
.reply-list {
  padding-bottom: 10px;
}
.reply-item {
  padding: 8px 0;
  border-top: 1px solid #f8f8f8;
  .avatar-placeholder.small {
    width: 28px;
    height: 28px;
    font-size: 12px;
  }
}
.view-replies-btn {
  font-size: 13px;
  color: #007aff;
  cursor: pointer;
  padding: 5px 0;
}
.delete-btn {
  color: #e5245e;
}

.highlight {
  background-color: #e6f7ff; /* 淡蓝色高亮 */
  border: 1px solid #91d5ff;
  border-radius: 8px;
}

.username-link {
  cursor: pointer;
}

.username-link,
.avatar-wrapper-link { // <-- 新增这个选择器
  cursor: pointer;
  text-decoration: none;
  color: inherit;
}
</style>